<script lang="ts" setup>
import { ElMessage, FormRules, FormInstance } from 'element-plus'
import { computed, defineAsyncComponent, reactive, ref, watchEffect } from 'vue'
import RefundAccountTypeFormItem from '@/components/basic/RefundAccountTypeFormItem.vue'
import { AliPayRefundData, BankRefundData } from '@/types/interface'
import dayjs from 'dayjs'
import { submitBalanceRefund } from '@/api/order'
import { AccountType } from '@/types/enum'
import { getToken, getPhone, getUserName } from '@/utils/cache/cookies'
import { useRoute } from 'vue-router'
const dialogVisible = ref<boolean>(false)
const createdTime = ref<string>('')
const remainRefundAmount = ref<number>(0)
const userId = ref<string>('')
const banlance = ref<number>(0)
const chargeAmount = ref<number>(0)
const form = reactive({
  orderNo: '',
  isAll: true,
  type: '余额',
  refundAmount: 0,
  accountType: 'Origin',
  refundReason: ''
})
const route = useRoute()
const formRef = ref<FormInstance | null>(null)
const rules: FormRules = {
  refundAmount: [{ required: true, message: '请输入退款金额', trigger: 'blur' }],
  refundReason: [{ required: true, message: '请输入退款原因', trigger: 'blur' }],
  type: [{ required: true, message: '请选择退款类型', trigger: 'blur' }],
  accountType: [{ required: true, message: '请选择退款方式', trigger: 'blur' }],
  orderNo: [{ required: true, message: '请选择退款订单', trigger: 'blur' }],
  isAll: [{ required: true, message: '请选择是否全额退款', trigger: 'blur' }]
}
const open = () => {
  dialogVisible.value = true
}
const setData = (
  orderId: string,
  time: string,
  amount: number,
  id: string,
  b: number,
  charge: number
) => {
  createdTime.value = time
  form.orderNo = orderId
  remainRefundAmount.value = amount
  userId.value = id
  banlance.value = b
  chargeAmount.value = charge
}
defineExpose({ open, setData })

/** 选择退款渠道时 支付宝数据或者银行卡数据 */
const AliAccountData = reactive<AliPayRefundData & Record<string, any>>({
  aliName: '',
  aliAccount: ''
})
const BankAccountData = reactive<BankRefundData & Record<string, any>>({
  bankName: '',
  bankBranchName: '',
  username: '',
  card: ''
})
/** 是否传入accountData */
const AccountData = computed(() => {
  if (form.accountType === 'Origin') return
  if (form.accountType === 'AliPay') {
    return AliAccountData
  } else {
    return BankAccountData
  }
})
/** 打开支付宝权限dialog */
const AliPayPermissionDialog = defineAsyncComponent(
  () => import('@/components/dialog/AliPayPermission.vue')
)
const AliPayPermissionDialogRef = ref<InstanceType<typeof AliPayPermissionDialog> | null>(null)
const handleOpen = () => {
  AliPayPermissionDialogRef.value?.open()
}
/** 判断时间差是否为三个月 用于判断是否原路退回 */
const isWithinThreeMonths = (dateTime1: string, dateTime2: string) => {
  // 使用 dayjs 解析传入的日期字符串
  const start = dayjs(dateTime1, 'YYYY-MM-DD HH:mm:ss')
  const end = dayjs(dateTime2, 'YYYY-MM-DD HH:mm:ss')

  // 计算两个时间相差的天数
  const dayDiff = Math.abs(start.diff(end, 'day'))

  // 判断天数差是否在 90 天以内（3 个月）
  return dayDiff <= 90
}
const apartTime = computed(() => {
  return isWithinThreeMonths(createdTime.value, dayjs().format('YYYY-MM-DD HH:mm:ss'))
})
const allowRefund = computed(() => {
  if (banlance.value >= remainRefundAmount.value) {
    return remainRefundAmount.value
  } else {
    return banlance.value
  }
})
watchEffect(() => {
  if (form.isAll) {
    form.refundAmount = allowRefund.value
  } else {
    form.refundAmount = 0
  }
})
const emits = defineEmits(['refresh'])
const reset = () => {
  formRef.value?.resetFields()
  dialogVisible.value = false
}
const submit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const res = await submitBalanceRefund({
          token: getToken() ?? '',
          refundPath: form.accountType as AccountType,
          refundReason: form.refundReason,
          orderNo: form.orderNo,
          refundAmount: form.refundAmount,
          userId: route.query.userId as string,
          contextData: AccountData.value
        })
        if (res.statusCode === '0') {
          ElMessage.success(res.data)
          emits('refresh')
          dialogVisible.value = false
        }
      } catch (error) {
        console.error(error)
      }
    }
  })
}
</script>

<template>
  <el-dialog title="余额退款申请" width="650px" v-model="dialogVisible">
    <el-form :model="form" ref="formRef" label-width="120px" :rules="rules">
      <el-form-item label="操作人:">
        <span>{{ getUserName() }}{{ getPhone() }}</span>
      </el-form-item>
      <el-form-item label="充值订单号:" prop="orderNo">
        <el-input v-model="form.orderNo" disabled />
      </el-form-item>
      <el-form-item label="全额退款:" prop="isAll">
        <el-radio-group v-model="form.isAll">
          <el-radio label="是" :value="true"></el-radio>
          <el-radio label="否" :value="false"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="退款类型:" prop="type">
        <el-select v-model="form.type" disabled>
          <el-option label="余额" value="余额"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="退款金额:" prop="refundAmount">
        <el-input v-model="form.refundAmount" :disabled="form.isAll" />
        <div>
          <span class="text-[12px] color-grey"
            >用户当前余额剩余{{ banlance }}元,当前充值订单为{{ chargeAmount }}元,可退金额为{{
              remainRefundAmount
            }}元</span
          >
        </div>
      </el-form-item>
      <refund-account-type-form-item
        -ali-value="AliPay"
        -bank-value="BankCard"
        -origin-value="Origin"
        v-model="form"
        v-model:alipay="AliAccountData"
        v-model:bank="BankAccountData"
        :apartTime="apartTime"
        @open="handleOpen"
      />
      <el-form-item label="退款原因:" prop="refundReason">
        <el-input v-model="form.refundReason" type="textarea" :autosize="{ minRows: 5 }" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submit">确认</el-button>
      <el-button @click="reset">取消</el-button>
    </template>
  </el-dialog>
</template>

<style scoped></style>
